package com.northpool.operator.common.xml;

import cn.hutool.core.util.XmlUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;
import org.w3c.dom.Document;

import javax.xml.xpath.XPathConstants;

@OperatorInfo(
        ref = "XmlPathOperator",
        name = "Xml抽取",
        description = "基于XPath表达式的Xml文本抽取"
)
@OutputParams({
        @OutputParam(ref = "execResult", name = "Xml抽取结果", type = TypeEnum.STRING)
})
public class XmlPathOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "XmlStr", name = "XML", desc = "XML文本", type = TypeEnum.STRING, required = true),
            @InputParam(ref = "exec", name = "表达式", desc = "XPath表达式", type = TypeEnum.STRING, required = true)
    })
    public XmlPathOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(XmlPathOperator.class,
                TestParamBuilder.aBuilder()
                        .param("XmlStr", "<?xml version=\"1.0\" encoding=\"utf-8\"?><returnsms><returnstatus>Success（成功）</returnstatus><message>ok</message><remainpoint>1490</remainpoint><taskID>885</taskID><successCounts>1</successCounts></returnsms>")
                        .param("exec", "//returnsms/message")
                        .build()
        );
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String xmlStr = paramTool.getStr("XmlStr");
        String exec = paramTool.getStr("exec");

        Document docResult = XmlUtil.readXML(xmlStr);
        Object val = XmlUtil.getByXPath(exec, docResult, XPathConstants.STRING);

        String execResult = "";
        if (val instanceof String) {
            execResult = (String) val;
        } else if (val instanceof Number) {
            execResult = String.valueOf(val);
        } else if (val != null) {
            throw new RuntimeException("暂不支持的数据抽取结果类型： " + execResult.getClass().getName());
        }
        this.result("execResult", execResult);
    }
}
